
<template>
	<div class="base-edit">
		<el-form-item
			label="添加子题"
			prop="smallQuestionList"
			:rules="{
				required: true,validator:checkOption
			}"
		>
			<el-button class="add-btn" type="primary" @click="addSubQuestion('add')">添加子题</el-button>
			<ve-table-drag :table-data="subQuestionList" :row-key="getRowKeys">
				<el-table-column
					type="index"
					label="序号"
					width="50"
					:index="function(index){return index+1}"
				/>
				<el-table-column
					label="试题类型"
					width="60"
					v-slot="{ row }"
				>
					{{ Dictionary.get('rc_questionType')[row.questionType] }}
				</el-table-column>
				<el-table-column label="题干" width="400" v-slot="{ row }">
					<ve-parse :article="row.questionTitle" />
				</el-table-column>
				<el-table-column
					label="试题状态"
					width="80"
					v-slot="{ row }"
				>
					{{ row.isAvailable === 'Y' ? '启用': '禁用' }}
				</el-table-column>
				<el-table-column label="操作" width="180" v-slot="{ row,$index }">
					<el-button type="text" @click="showKnowledgeDeleteDialog(row)">
						<span style="padding-right:3px">知识点</span>({{ row.knowledgeList ?row.knowledgeList.length:0 }})
					</el-button>
					<el-button type="text" @click="addSubQuestion('edit',$index,row)">编辑</el-button>
					<el-button
						type="text"
						class="errText"
						v-if="row.isAvailable === 'Y'"
						@click="onAvailableQuestion('N',$index)"
					>
						禁用
					</el-button>
					<el-button
						type="text"
						v-if="row.isAvailable === 'N'"
						@click="onAvailableQuestion('Y',$index)"
					>
						启用
					</el-button>
					<el-button type="text" @click="onDeleteQuestion($index,row)">删除</el-button>
					<i class="el-icon-rank" style="font-size: 18px; vertical-align: middle;margin-left: 8px;" />
				</el-table-column>
			</ve-table-drag>
		</el-form-item>
		<!-- 添加子题弹窗 -->
		<ve-dialog
			title="添加子题"
			width="1100px"
			v-if="showAdd"
			class="sq-dialog"
			:show.sync="showAdd"
			append-to-body
		>
			<edit-frame
				ref="subEditRef"
				:type="type"
				:question-data="subQuestion"
				:parent-type="parentType"
				:show-preview="false"
				@sub-save="onSubSave"
			/>
		</ve-dialog>
		<!-- 查看知识点弹窗 -->
		<knowledge-delete-dialog
			v-if="isShowKnowledgeDeleteDialog"
			:visibly.sync="isShowKnowledgeDeleteDialog"
			v-model="subQuestion.knowledgeList"
		/>
	</div>
</template>

<script >
import KnowledgeDeleteDialog from "@rc/pages/components/knowledge-delete-dialog/index.vue";
	export default {
		name: "base-edit-table",
		props: {
			parentType: {
				//组合题中大题类型
				type: String,
				default:''
			},
			list: {
				type: Array,
				default: () => []
			},
			optionList: {//配伍题的选项
				type: Array,
				default: () => []
			},
            basicInfo: {
				type: Object,
				default: () => {}
			},
			tagInfo: {
				type: Object,
				default: () => {}
			},
		},
		components: {
			EditFrame: () => import("@rc/pages/questions/components/edit-frame/index.vue"),
            KnowledgeDeleteDialog
		},
		data() {
			return {
				showAdd: false,
				subQuestionList: [],
				subQuestion: {},
				type: "",
				index: 0,
                isShowKnowledgeDeleteDialog:false,
                init:false,//子题信息初始化是否完成
                deleteResourceIds:[]//被删除的小题资源id
			};
		},
        watch:{
            'basicInfo.projectId':{//监听大题基本属性-项目改变
                deep:true,
                handler(){
                    this.init && this.onBasicInfoChange('projectId');
                }
            },
            'basicInfo.subjectId':{//监听大题基本属性-章节改变
                handler(){
                    this.init && this.onBasicInfoChange('subjectId');
                }
            },
            'basicInfo.chapterIds':{//监听大题基本属性改变
                deep:true,
                handler(){
                    this.init && this.onBasicInfoChange('chapterIds');
                }
            },
            'basicInfo.knowledgeList':{//监听大题基本属性-知识点改变
                deep:true,
                handler(){
                    this.init && this.onBasicInfoChange('knowledgeList');
                }
            },
            'basicInfo.questionDeveloperId':{//监听大题基本属性-研发人改变
                handler(){
                    this.init && this.onBasicInfoChange('questionDeveloperId');
                }
            },
            'tagInfo.applicableYear':{//监听大题标签属性-试题年份改变
                deep:true,
                handler(){
                    this.init && this.onTagInfoChange('applicableYear');
                }
            },
            'tagInfo.areaIds':{//监听大题标签属性-地区改变
                deep:true,
                handler(){
                    this.init && this.onTagInfoChange('areaIds');
                }
            },
            'tagInfo.labelList':{//监听大题标签属性-试题系统标签改变
                deep:true,
                immediate:true,
                handler(newList,oldList){
                    if(newList && oldList){
                        let changeLabelList = [];//找到变化的系统标签，
                        newList.forEach(newLabel=>{
                            let oldLabel = oldList.find(old=>old.labelId === newLabel.labelId);
                            if(oldLabel && oldLabel.labelDetailId !== newLabel.labelDetailId){
                                changeLabelList.push(newLabel);
                            }
                        });
                        this.init && this.onTagInfoChange('labelList', changeLabelList);
                    }
                }
            },
            //大题选项改变-针对配伍题
            'optionList':{
                deep:true,
                handler(){
                    this.parentType==='C'&& this.onOptionListChange();
                }
            },
            list:{
               deep:true,
               immediate:true,
                handler(){
                    this.subQuestionList = JSON.parse(JSON.stringify(this.list));
                    this.init = true;
                }
            },
            subQuestionList:{
                deep:true,
                handler(list) {
                    this.$emit("sub-change",list);
                }
            }
        },
		methods: {
            checkOption(rule, value, callback) {
                if (!this.subQuestionList.length){
                    return callback(new Error("请添加子题"));
                }
                callback();
            },
            //大题基本属性改变,小题跟着改变
            onBasicInfoChange(prop){
                this.subQuestionList = this.subQuestionList.map(question=>{
                    let changeInfo = {};
                     const basicInfo = JSON.parse(JSON.stringify(this.basicInfo));
                    if(prop==='projectId'){
                        changeInfo.projectId = basicInfo.projectId;
                        changeInfo.projectName = basicInfo.projectName;
                    }else if(prop==='subjectId'){
                        changeInfo.subjectId = basicInfo.subjectId;
                        changeInfo.subjectName = basicInfo.subjectName;
                    }else if(prop==='chapterIds'){
                        changeInfo.chapterIds = basicInfo.chapterIds;
                        changeInfo.chapterList = basicInfo.chapterList;
                    }else if(prop==='knowledgeList'){
                        changeInfo.knowledgeList = basicInfo.knowledgeList;
                    }else if(prop==='questionDeveloperId'){
                        changeInfo.questionDeveloperId = basicInfo.questionDeveloperId;
                        changeInfo.questionDeveloperName = basicInfo.questionDeveloperName;
                    }
                    question = {
                        ...question,
                        ...changeInfo
                    };
                    return question;
                });
            },
            //大题标签属性改变，小题标签属性对应改变
            onTagInfoChange(prop,value){
                this.subQuestionList = this.subQuestionList.map((question)=>{
                    const tagInfo = JSON.parse(JSON.stringify(this.tagInfo));
                    let changeInfo = {};
                    if(prop==='applicableYear'){
                        changeInfo.applicableYear = tagInfo.applicableYear;
                    }else if(prop==='areaIds'){
                        changeInfo.areaIds =tagInfo.areaIds;
                        changeInfo.areaList = tagInfo.areaList;
                    }else if(prop==='labelList'){
                        let questionLabelList = question.labelList;
                        value.forEach(newLabel=>{
                            let oldLabel = questionLabelList.find(old=>old.labelId === newLabel.labelId);
                            if(oldLabel){//替换新值
                                oldLabel.labelDetailId =newLabel.labelDetailId;
                                oldLabel.labelDetailName =newLabel.labelDetailName;
                            }else {//将新标签加入
                                questionLabelList.push(newLabel);
                            }
                        });
                        changeInfo.labelList = questionLabelList;
                    }
                    question = {
                        ...question,
                        ...changeInfo
                    };
                    return question;
                });
            },
            /**
             * 大题选项改变-针对配伍题
             * 当选项内容修改，小题选项自动同步，当删除了选项，
             */
            onOptionListChange(){
                if(!this.optionList){
                    return;
                }
                this.subQuestionList.forEach((question)=>{
                    const optionList = JSON.parse(JSON.stringify(this.optionList));
                    let answerSeq = 0;
                    const subOption = question.optionList;
                    //获取原来选择的正确答案
                    const optionSeqs = subOption.filter(option=>option.isAnswer==='Y').map(option=>option.optionSeq);
                    optionList.forEach((option)=>{
                        option.isAnswer = 'N';
                        option.answerSeq = 0;
                        if(optionSeqs.includes(option.optionSeq)){
                            answerSeq++;
                            option.isAnswer = 'Y';
                            option.answerSeq = answerSeq;
                        }
                    });
                    question.optionList = optionList;
                    question.answer = this.resetAnswer(question.optionList);
                });
            },
            //仅针对配伍题-下小题（单选题/多选题/不定项选择题）选项改变后重置答案answer
            resetAnswer(optionList){
                const answerOptionList = optionList.filter( option=>option.isAnswer==='Y');
                const answerList =  answerOptionList.map(option=>option.optionSeq);
                return answerList.join(',');
            },
            //点击查看知识点详情
            showKnowledgeDeleteDialog(row){
                if(!row.knowledgeList || row.knowledgeList.length===0){
                    this.$message.warning("没有关联知识点");
					return;
                }
                this.isShowKnowledgeDeleteDialog = true;
                this.subQuestion = row;
            },
            //检查是否重复
            isRepeat(arr) {
				let hash = {};
				for (let i in arr) {
					if (hash[arr[i]["answerOption"]]) {
						return true;
					}
					hash[arr[i]["answerOption"]] = true;
				}
				return false;
			},
			addSubQuestion(type, index, row) {
				const { projectId, subjectId } = this.basicInfo;
				if (!projectId || !subjectId) {
					this.$message.warning("请选择项目科目");
					return;
				}
                //选中不能重复且为空
                if(this.parentType==='C') {
                    if (this.optionList.some(option=>option.answerOption === undefined || option.answerOption === "")){
                        this.$message.warning("选项不能为空");
                        return;
                    }
                    if( this.isRepeat(this.optionList)) {
                        this.$message.warning("选项不能重复");
                        return;
                    }
                }
				this.type = type;
				if (type === "edit") {
					this.index = index;
                    this.subQuestion = this.getQuestion(row);
				} else {
					this.subQuestion = {
						basicInfo: this.basicInfo,
						tagInfo: this.tagInfo,
                        optionList: this.optionList
					};
				}
				this.showAdd = true;
			},
			//保存子题
			onSubSave(question) {
				if (this.type === "add") {
                    question.isAvailable = 'Y';//默认启用
					this.subQuestionList.push(question);
				} else {
					this.$set(this.subQuestionList, this.index, question);
				}
				this.showAdd = false;
			},
			//删除子题
			onDeleteQuestion(index,row) {
                //添加确认框
                this.$confirm('确认删除该小题吗', '提示', {
                    confirmButtonText:'确定',
                    cancelButtonText:'取消',
                    type: 'warning'
                }).then(() => {
                    //如果删除的是已入库的子题则统计下试题id
                    if(row.resourceId){
                        this.deleteResourceIds.push(row.resourceId);
                        this.$emit("del-sub",this.deleteResourceIds);
                    }
                    this.subQuestionList.splice(index,1);
                });

			},
			//启用禁用
			onAvailableQuestion(isAvailable, $index) {
                let question = this.subQuestionList[$index];
                question.isAvailable = isAvailable;
                this.$set(this.subQuestionList, $index, question);
			},
            //将子题处理成可以展示在编辑组件内的格式
            getQuestion(resource){
                let {projectId,projectName,subjectId,subjectName,questionDeveloperId,questionDeveloperName,areaList,applicableYear,knowledgeList,labelList,chapterList} =  resource;
                //处理标签信息格式
                if(!labelList){
                    labelList = [];
                }
                let basicInfo = {
                    projectId:Array.isArray(projectId)?projectId:[projectId],
                    projectName,
                    subjectId,
                    subjectName,
                    knowledgeList:knowledgeList||[],
                    questionDeveloperId,
                    questionDeveloperName,
                    chapterIds:chapterList?chapterList.map(chapter=>chapter.chapterId):[],
                    chapterList
                };
                let tagInfo = {
                    areaIds:areaList?areaList.map(area=>area.cityId):[],
                    applicableYear,
                    labelList:labelList||[]
                };
                return {
                    ...resource,
                    basicInfo,
                    tagInfo
                };
            },
            // 确定唯一的key值
            getRowKeys(row) {
                return row.questionType+row.questionTitle+Math.random();
            },
		}
	};
</script>
<style lang="less" scoped>

    .base-edit{
        .add-btn {
            margin-bottom: 10px;
        }
        /deep/ .el-table__empty-block {
            width: 100% !important;
        }
        /deep/ img{
            max-width: 50px;
            max-height: 50px;
        }
        /deep/ .el-button+.el-button{
            margin-left: 5px;
        }
        /deep/.cell {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
         /deep/ .el-icon-rank{
            margin-top: -3px;
        }
    }
</style>
